package com.example.demo.util;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class TimeParser {

    // 上课时间表
    private static final String[] START_TIMES = {
            "08:00", "08:55", "10:10", "11:05", "14:30", "15:25", "16:40", "17:35", "19:10", "20:05", "21:00"
    };

    // 将字符串时间转换为LocalDateTime
    public static LocalDateTime parseCourseTime(String timeStr) {
        try {
            // 尝试解析标准格式（如"yyyy-MM-dd HH:mm:ss"）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            return LocalDateTime.parse(timeStr, formatter);
        } catch (Exception e) {
            // 处理自定义格式（如"周一 3-4节"）
            return parseCustomFormat(timeStr);
        }
    }

    // 处理自定义时间格式（如"周一 3-4节"）
    private static LocalDateTime parseCustomFormat(String timeStr) {
        // 分割字符串，提取星期和节次
        String[] parts = timeStr.split(" ");
        String dayOfWeekStr = parts[0]; // 星期几，如"周一"
        int section = Integer.parseInt(parts[1].charAt(0) + ""); // 节次，如3

        // 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        DayOfWeek currentDayOfWeek = now.getDayOfWeek();

        // 将星期几的中文转换为DayOfWeek枚举
        DayOfWeek targetDayOfWeek = getDayOfWeek(dayOfWeekStr);

        // 计算目标日期（如果课程是下周的，则加7天）
        int daysToAdd = targetDayOfWeek.getValue() - currentDayOfWeek.getValue();
        if (daysToAdd <= 0) {
            daysToAdd += 7;
        }

        // 获取课程开始时间
        String startTimeStr = START_TIMES[section - 1];
        LocalDateTime startTime = now.plusDays(daysToAdd).withHour(0).withMinute(0).withSecond(0).withNano(0);
        startTime = startTime.withHour(Integer.parseInt(startTimeStr.substring(0, 2)));
        startTime = startTime.withMinute(Integer.parseInt(startTimeStr.substring(3, 5)));

        return startTime;
    }

    // 将星期几的中文转换为DayOfWeek枚举
    private static DayOfWeek getDayOfWeek(String dayOfWeekStr) {
        switch (dayOfWeekStr) {
            case "周一":
                return DayOfWeek.MONDAY;
            case "周二":
                return DayOfWeek.TUESDAY;
            case "周三":
                return DayOfWeek.WEDNESDAY;
            case "周四":
                return DayOfWeek.THURSDAY;
            case "周五":
                return DayOfWeek.FRIDAY;
            case "周六":
                return DayOfWeek.SATURDAY;
            case "周日":
                return DayOfWeek.SUNDAY;
            default:
                throw new IllegalArgumentException("Invalid day of week: " + dayOfWeekStr);
        }
    }
}